package cn.itsource.basic.basic.service.impl;

import cn.itsource.basic.basic.domain.Basedomain;
import cn.itsource.basic.basic.domain.dto.LoginDto;
import cn.itsource.basic.basic.service.ILoginService;
import cn.itsource.basic.exception.CustomException;
import cn.itsource.basic.utils.MD5Utils;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;
   /*
    redis必须去序列化才能使用？
    public class Logininfo extends Basedomain implements Serializable
    让这个domain去实现Serializable接口
    */
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Object accountLogin(LoginDto dto) {
        //1.校验用户名与密码是否非空
        if(StringUtils.isEmpty(dto.getUsername())||StringUtils.isEmpty(dto.getPassword())){
            throw new CustomException("传入参数异常!");
        }
        //2.查询是否有这个用户
        Logininfo logininfo = logininfoMapper.selectByUsernameAndType(dto.getUsername(),dto.getType());
        if(logininfo==null){
            throw new CustomException("用户为空,请去注册");
        }
        //3.将前端传过来的密码与数据库查询到的盐值进行拼接后，再和数据里的加密密码进行对比，看看密码是否输入正确
        String newPassword = MD5Utils.encrypByMd5(dto.getPassword() + logininfo.getSalt());
        if(!logininfo.getPassword().equals(newPassword)){
            throw new CustomException("用户名或密码错误");
        }
        //4.生成uuid存储到redis中,uuid是key,logininfo对象是value,过期时间30分钟
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //5.将uuid,logininfo返回给前端
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        System.out.println(map);
        return map;
    }

    public static void main(String[] args) {
        System.out.println(MD5Utils.encrypByMd5("123IDcgmoZDrjTFUkKjNQrACxkNreW9OF7m"));
    }
}
